package com.dragonfly.shutter.services;

import java.util.Date;

import com.dragonfly.shutter.DAOs.AlbumDAO;
import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.FriendDAO;
import com.dragonfly.shutter.DAOs.PictureAlbumDAO;
import com.dragonfly.shutter.beans.Album;
import com.dragonfly.shutter.beans.BrowseLog;

/**
 * 相册服务类
 * @author 黄挺
 *
 */
public class AlbumService {
	private AlbumDAO albumDAO;
	private FriendDAO friendDAO;
	private BrowseLogDAO browseLogDAO;
	private PictureAlbumDAO pictureAlbumDAO;
	
	/**
	 * 相册中心服务函数
	 * @param albumID 相册ID
	 * @param userID 用户ID
	 * @param requestURL 请求URL
	 * @return 用户相册ID为albumID的相册
	 * @throws Exception 相册访问权限受限
	 */
	public Album doService(Integer albumID, Integer userID, String requestURL) throws Exception{
		//生成日志Bean
		BrowseLog browseLog = new BrowseLog();
		
		if(userID != null)
			browseLog.setUserID(userID);
		
		browseLog.setBrowseTime(new Date(System.currentTimeMillis()));
		browseLog.setUrl(requestURL);
		
		Album album = doDBOperate(albumID, browseLog);
		
		//访问权限检查
		if(album.getFlagPermission() == "private" && 
				(userID == null || userID != album.getOwner().getUserID())){
			throw new Exception("您不是这个相册的所有者，无权访问该相册");
		}
		
		if(album.getFlagPermission() == "friend" &&
				 ( userID != album.getOwner().getUserID()  || friendDAO.selectOneFriend(album.getOwner().getUserID(), userID) == null)){
			throw new Exception("您不是这个相册的所有者或者是所有者的好友，无权访问该相册");
		}
		
		return album;
	}
	
	/**
	 * 相册中心数据库操作函数
	 * @param albumID 相册ID
	 * @param browseLog 日志Bean
	 * @return 用户相册ID为albumID的相册
	 * @throws Exception 未知的相册
	 */
	public Album doDBOperate(Integer albumID, BrowseLog browseLog) throws Exception{
		Album album = albumDAO.selectAlbumByID(albumID);
		
		//未知的相册
		if(album == null ){
			throw new Exception("未知的相册");
		}
		
		browseLogDAO.insertBrowseLog(browseLog);
		album.setPictureOrder(pictureAlbumDAO.selectPagedPictureAlbum(albumID, 0, 10));
		return album;
	}

	public void setAlbumDAO(AlbumDAO albumDAO) {
		this.albumDAO = albumDAO;
	}

	public void setFriendDAO(FriendDAO friendDAO) {
		this.friendDAO = friendDAO;
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}

	public void setPictureAlbumDAO(PictureAlbumDAO pictureAlbumDAO) {
		this.pictureAlbumDAO = pictureAlbumDAO;
	}
}
